package com.aracky.system.service.impl;

import com.aracky.common.util.ComUtil;
import com.aracky.system.model.entity.SysUser;
import com.aracky.system.model.entity.SysUserRole;
import com.aracky.system.mapper.SysUserRoleMapper;
import com.aracky.system.service.SysUserRoleService;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.*;
import java.util.function.Function;
import java.util.stream.Collectors;

/**
 * <p>
 * 用户和角色关联表 服务实现类
 * </p>
 *
 * @author zzp
 * @since 2022-07-15 02:05:32
 */
@Service
public class SysUserRoleServiceImpl extends ServiceImpl<SysUserRoleMapper, SysUserRole> implements SysUserRoleService {
    @Override
    public void saveBatchUserRole(List<SysUserRole> userRoleList) {
        if(ComUtil.isNullList(userRoleList)){
            return;
        }

        //先查询是否存在当前绑定的信息
        List<Long> userIdList = userRoleList.stream().map(SysUserRole::getUserId).collect(Collectors.toList());
        LambdaQueryWrapper<SysUserRole> userRoleLambdaQueryWrapper =
                Wrappers.<SysUserRole>lambdaQuery().in(SysUserRole::getUserId,userIdList);
        List<SysUserRole> dbUserRoleList = this.list(userRoleLambdaQueryWrapper);
        Map<String, SysUserRole> userRoleMap = dbUserRoleList.stream()
                .collect(Collectors.toMap(k -> k.getRoleId() + String.valueOf(k.getUserId()), Function.identity(),(value1,value2)->value2));

        //筛选出不存在数据库的数据进行保存
        List<SysUserRole> saveList = userRoleList.stream().filter(sysUserRole ->
                !userRoleMap.containsKey(String.valueOf(sysUserRole.getRoleId()) + sysUserRole.getUserId()))
                .collect(Collectors.toList());

        if(ComUtil.isNullList(saveList)){
            return;
        }
        //去掉重复数据
        saveList =   saveList.stream()
                .collect(Collectors.collectingAndThen(Collectors.toCollection(
                        () -> new TreeSet<>(Comparator.comparing(SysUserRole::getUserId).thenComparing(SysUserRole::getRoleId))),
                        ArrayList::new));
        this.saveBatch(saveList);
    }
}
